<template>
  <div class="hospital-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="院区选择"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />

    <!-- 院区选择内容 -->
    <div class="hospital-content">
      <div class="selection-header">
        <h3>请选择院区</h3>
        <p>选择您要前往的医院院区</p>
      </div>

      <!-- 搜索框 -->
      <div class="search-section">
        <van-search
          v-model="searchKeyword"
          placeholder="搜索院区名称或地址"
          @search="onSearch"
          @input="onSearchInput"
          show-action
        >
          <template #action>
            <div @click="getCurrentLocation" class="location-btn">
              <van-icon name="location-o" size="16" />
              <span>定位</span>
            </div>
          </template>
        </van-search>
      </div>

      <!-- 加载状态 -->
      <van-loading v-if="loading" class="loading-center" size="24px" vertical>
        加载中...
      </van-loading>

      <!-- 院区列表 -->
      <div class="hospital-list" v-if="!loading">
        <!-- 空状态 -->
        <van-empty 
          v-if="hospitalList.length === 0 && !loading"
          image="search"
          description="暂无符合条件的院区"
        />
        
        <!-- 院区项目 -->
        <div 
          v-for="hospital in hospitalList" 
          :key="hospital.id"
          class="hospital-item"
          @click="selectHospital(hospital)"
        >
          <div class="hospital-icon">
            <van-icon name="location-o" size="24" color="#1989fa" />
          </div>
          <div class="hospital-info">
            <div class="hospital-header">
              <h4>{{ hospital.name }}</h4>
              <span v-if="hospital.distance" class="distance">
                {{ formatDistance(hospital.distance) }}
              </span>
            </div>
            <p>{{ hospital.address }}</p>
            <p v-if="hospital.phone" class="phone">{{ hospital.phone }}</p>
            <p v-if="hospital.description" class="description">{{ hospital.description }}</p>
            <div class="hospital-tags">
              <span 
                v-for="tag in hospital.tags" 
                :key="tag"
                class="tag"
              >
                {{ tag }}
              </span>
              <span v-if="hospital.isSelfServiceEnabled" class="tag self-service">
                自助开单
              </span>
            </div>
          </div>
          <div class="hospital-arrow">
            <van-icon name="arrow" size="16" color="#c8c9cc" />
          </div>
        </div>
      </div>

      <!-- 温馨提示 -->
      <div class="tips-section">
        <div class="tips-header">
          <van-icon name="info-o" size="16" color="#ff976a" />
          <span>温馨提示</span>
        </div>
        <ul class="tips-list">
          <li>请根据您的实际需求选择合适的院区</li>
          <li>不同院区的科室设置和检查项目可能有所差异</li>
          <li>建议选择距离较近的院区，方便您前往检查</li>
          <li>如有疑问，可联系客服咨询</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Toast, Dialog } from 'vant'
import { apiService, type HospitalArea } from '@/api'

/**
 * 院区选择页面组件
 * 用户可以选择不同的医院院区，支持搜索和定位功能
 */

const router = useRouter()

/**
 * 响应式数据
 */
const hospitalList = ref<HospitalArea[]>([])
const loading = ref(false)
const searchKeyword = ref('')
const userLocation = ref<{ longitude: number; latitude: number } | null>(null)

/**
 * 防抖搜索定时器
 */
let searchTimer: number | null = null

/**
 * 获取院区列表数据
 */
const fetchHospitalAreas = async () => {
  try {
    loading.value = true
    const params = {
      searchKeyword: searchKeyword.value || undefined,
      userLongitude: userLocation.value?.longitude,
      userLatitude: userLocation.value?.latitude
    }
    
    const response = await apiService.getSelfServiceHospitalAreas(params)
    
    if (response.code === 200) {
      hospitalList.value = response.data || []
    } else {
      Toast.fail(response.message || '获取院区列表失败')
      hospitalList.value = []
    }
  } catch (error) {
    console.error('获取院区列表失败:', error)
    Toast.fail('网络错误，请稍后重试')
    hospitalList.value = []
  } finally {
    loading.value = false
  }
}

/**
 * 获取用户当前位置
 */
const getCurrentLocation = () => {
  if (!navigator.geolocation) {
    Toast.fail('您的浏览器不支持定位功能')
    return
  }

  Toast.loading({
    message: '正在获取位置...',
    forbidClick: true,
    duration: 0
  })

  navigator.geolocation.getCurrentPosition(
    (position) => {
      Toast.clear()
      userLocation.value = {
        longitude: position.coords.longitude,
        latitude: position.coords.latitude
      }
      Toast.success('定位成功')
      fetchHospitalAreas()
    },
    (error) => {
      Toast.clear()
      console.error('定位失败:', error)
      
      let errorMessage = '定位失败'
      switch (error.code) {
        case error.PERMISSION_DENIED:
          errorMessage = '定位权限被拒绝，请在浏览器设置中允许定位'
          break
        case error.POSITION_UNAVAILABLE:
          errorMessage = '无法获取位置信息'
          break
        case error.TIMEOUT:
          errorMessage = '定位超时，请重试'
          break
      }
      
      Dialog.alert({
        title: '定位失败',
        message: errorMessage
      })
    },
    {
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 300000
    }
  )
}

/**
 * 搜索输入处理（防抖）
 */
const onSearchInput = () => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  
  searchTimer = setTimeout(() => {
    fetchHospitalAreas()
  }, 500)
}

/**
 * 搜索按钮点击处理
 */
const onSearch = () => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  fetchHospitalAreas()
}

/**
 * 格式化距离显示
 * @param distance 距离（公里）
 */
const formatDistance = (distance: number): string => {
  if (distance < 1) {
    return `${Math.round(distance * 1000)}m`
  } else {
    return `${distance.toFixed(1)}km`
  }
}

/**
 * 点击返回按钮
 */
const onClickLeft = () => {
  router.back()
}

/**
 * 选择医院院区
 * @param hospital 选中的医院信息
 */
const selectHospital = (hospital: HospitalArea) => {
  console.log('选择医院院区:', hospital.name)
  Toast({
    message: `已选择 ${hospital.name}`,
    position: 'middle',
    duration: 1000
  })
  
  // 跳转到开单申请页面，并传递医院信息
  setTimeout(() => {
    router.push({
      path: '/order-application',
      query: {
        hospitalId: hospital.id.toString(),
        hospitalName: hospital.name,
        hospitalAddress: hospital.address
      }
    })
  }, 1000)
}

/**
 * 组件挂载时获取数据
 */
onMounted(() => {
  fetchHospitalAreas()
})
</script>

<style scoped>
.hospital-container {
  height: 100%;
  max-height: 100vh;
  background-color: #f7f8fa;
  display: flex;
  flex-direction: column;
  /* 确保内容不会溢出手机屏幕 */
  max-width: 100%;
  box-sizing: border-box;
  overflow: hidden;
}

.hospital-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.selection-header {
  text-align: center;
  margin-bottom: 24px;
}

.selection-header h3 {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.selection-header p {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.search-section {
  margin-bottom: 16px;
}

.location-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 12px;
  background: #1989fa;
  color: white;
  border-radius: 6px;
  font-size: 12px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.location-btn:hover {
  background: #1976d2;
}

.loading-center {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
}

.hospital-list {
  margin-bottom: 24px;
}

.hospital-item {
  display: flex;
  align-items: center;
  padding: 16px;
  margin-bottom: 12px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
}

.hospital-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.hospital-item:active {
  transform: translateY(0);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.hospital-icon {
  margin-right: 12px;
  width: 40px;
  height: 40px;
  background: #e8f4fd;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.hospital-info {
  flex: 1;
}

.hospital-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.hospital-info h4 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0;
  flex: 1;
}

.distance {
  font-size: 12px;
  color: #1989fa;
  font-weight: 500;
  background: #f0f9ff;
  padding: 2px 6px;
  border-radius: 8px;
  border: 1px solid #e1f5fe;
}

.hospital-info p {
  font-size: 13px;
  color: #666;
  margin: 0 0 4px 0;
  line-height: 1.4;
}

.phone {
  color: #1989fa !important;
  font-weight: 500;
}

.description {
  font-size: 12px !important;
  color: #999 !important;
  margin-bottom: 8px !important;
}

.hospital-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.tag {
  padding: 2px 8px;
  background: #f0f9ff;
  color: #1989fa;
  font-size: 11px;
  border-radius: 10px;
  border: 1px solid #e1f5fe;
}

.tag.self-service {
  background: #f6ffed;
  color: #52c41a;
  border-color: #b7eb8f;
  font-weight: 500;
}

.hospital-arrow {
  margin-left: 8px;
}

.tips-section {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.tips-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.tips-header span {
  margin-left: 6px;
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.tips-list {
  margin: 0;
  padding-left: 16px;
}

.tips-list li {
  font-size: 13px;
  color: #666;
  line-height: 1.6;
  margin-bottom: 6px;
}

.tips-list li:last-child {
  margin-bottom: 0;
}

/* 手机外框内适配 */
:deep(.van-nav-bar) {
  position: sticky;
  top: 0;
  z-index: 100;
  background: #fff;
  border-bottom: 1px solid #ebedf0;
}

/* 响应式设计 */
@media (max-width: 375px) {
  .hospital-content {
    padding: 12px;
  }
  
  .hospital-item {
    padding: 12px;
    margin-bottom: 10px;
  }
  
  .hospital-info h4 {
    font-size: 15px;
  }
  
  .hospital-info p {
    font-size: 12px;
  }
  
  .tag {
    font-size: 10px;
    padding: 1px 6px;
  }
  
  .tips-section {
    padding: 12px;
  }
}
</style>